package com.bridgeintelligent.tag.customer.controller;

import com.alibaba.fastjson.JSONObject;
import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.customer.entity.CustomersCodes;
import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.entity.HandlePage;
import com.bridgeintelligent.tag.customer.entity.Result;
import com.bridgeintelligent.tag.customer.exception.CustomersException;
import com.bridgeintelligent.tag.customer.mapper.CustomersMapper;
import com.bridgeintelligent.tag.customer.model.ShareModel;
import com.bridgeintelligent.tag.customer.pojo.*;
import com.bridgeintelligent.tag.customer.service.CustomersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "客群管理")
@AllArgsConstructor
@RestController
@RequestMapping("/api/customers")
@Slf4j
public class CustomersController {

    private CustomersService customersService;
    private CustomersMapper customersMapper;

    @ApiOperation("修改客群")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", name = "customersModel", value = "客群信息")})
    @PostMapping("/update")
    public Result updateCustomers(@RequestBody CustomersModel customersModel) {
        try {
            //校验角色名是否超过长度
            if (customersModel.getCustomersName()
                              .length() > 100) {
                throw new CustomersException(ExceptionCodes.CUSTOMERS_80001);
            }
            //校验用户名是否重复
            boolean success = customersService.checkCustomersName(customersModel.getCustomersName());
            JSONObject queryCriteria = JSONObject.parseObject(customersModel.getQueryCriteria());
            if (success) {
                customersService.updateCustomers(customersModel.getCustomersId(), customersModel.getCustomersName(), customersModel.getCustomersDes(), customersModel.getDateType(),customersModel.getStatus(), customersModel.getShareChannelIds(), queryCriteria,customersModel.getIndexId());
            } else {
                //查询用户名是否修改
                String oldCustomersName = customersService.findCustomersNameById(customersModel.getCustomersId());
                //原来用户未修改用户名
                if (oldCustomersName.equals(customersModel.getCustomersName())) {
                    //修改用户
                    customersService.updateCustomers(customersModel.getCustomersId(), customersModel.getCustomersName(), customersModel.getCustomersDes(), customersModel.getDateType(),customersModel.getStatus(), customersModel.getShareChannelIds(), queryCriteria,customersModel.getIndexId());
                } else {
                    return new Result(-1, "客群名称重复，请修改客群名称后重新提交！");
                }
            }
            return new Result(CustomersCodes.SUCCESS);
        } catch (CustomersException e) {
            return new Result(e.getCode(), "操作失败");
        }
    }

    @ApiOperation("新增客群")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", name = "customersModel", value = "客群信息")})
    @PostMapping("/add")
    public Result addCustomers(@RequestBody CustomersModel customersModel) {
        try {
            //校验客群名是否超过长度
            if (customersModel.getCustomersName()
                              .length() > 100) {
                throw new CustomersException(ExceptionCodes.CUSTOMERS_80001);
            }
            //校验客群名是否重复
            boolean success = customersService.checkCustomersName(customersModel.getCustomersName());
            if (success) {
                //新建客群
                customersService.addCustomers(customersModel);
            } else {
                return new Result(-1, "客群名称重复，请修改客群名称后重新提交！");
            }
            return new Result(CustomersCodes.SUCCESS);
        } catch (CustomersException e) {
            return new Result(e.getCode(), "操作失败");
        }
    }

    /**
     * 删除客群
     *
     * @return
     */
    @ApiOperation("删除客群")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id")})
    @GetMapping("/delCustomers")
    public Result delCustomers(String customersId) {
        customersService.delCustomers(customersId);
        return new Result(CustomersCodes.SUCCESS);
    }

    /**
     * 获取单个客群的详细信息
     *
     * @return
     */
    @ApiOperation("获取单个客群的详细信息")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id")})
    @GetMapping("/findOneById")
    public Result findOneById(String customersId) {
        Customers customers = customersService.findOneById(customersId);
        if (customers.getCustomersId() != null){
            return new Result(CustomersCodes.SUCCESS, customers);
        }else{
            return new Result(-1,"客群不存在");
        }

    }


    /**
     * 获取客群列表
     *
     * @return
     */
    @ApiOperation("获取客群列表")
    @GetMapping("/list")
    public Result list(@ModelAttribute ListQueryModel model) {
        if(model.getPageNumber() == null){
            model.setPageNumber(1);
        }
        if(model.getPageSize() == null){
            model.setPageSize(10);
        }
        return customersService.list(model);
    }


    @ApiOperation("index-获取索引下的客群列表")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", name = "indexId", value = "索引ID",required = false),
        @ApiImplicitParam(paramType = "query", name = "customersName", value = "客群名称",required = false)
    })
    @GetMapping("/indexCustomerList")
    public Result indexCustomerList(String indexId,String customersName) {

        return customersService.indexCustomerList(indexId,customersName);

    }



    /**
     * 获取客群列表---导出下发专用
     *
     * @return
     */
    @ApiOperation("导出下发专用-获取客群列表")
    @GetMapping("/exportlist")
    public Result exportlist(@ModelAttribute ListQueryModel model) {
        if(model.getPageNumber() == null){
            model.setPageNumber(1);
        }
        if(model.getPageSize() == null){
            model.setPageSize(Integer.MAX_VALUE);
        }
        return customersService.list(model);
    }

    @ApiOperation("共享客群列表")
    @GetMapping("/sharedList")
    public Result sharedList(@ModelAttribute ListQueryModel model) {
        if(model.getPageNumber() == null){
            model.setPageNumber(1);
        }
        if(model.getPageSize() == null){
            model.setPageSize(10);
        }
        return customersService.sharedList(model);
    }

    @ApiOperation("私有客群列表")
    @GetMapping("/privateList")
    public Result privateList(@ModelAttribute ListQueryModel model) {
        if(model.getPageNumber() == null){
            model.setPageNumber(1);
        }
        if(model.getPageSize() == null){
            model.setPageSize(10);
        }
        return customersService.privateList(model);
    }

    @ApiOperation("查询所有渠道列表")
    @GetMapping("/findAllChannel")
    public Result findAllChannel() {
        List<Channel> channelList = customersService.findAllChannel();
        return new Result(CustomersCodes.SUCCESS, channelList);
    }

    /**
     * 获取我的客群列表
     *
     * @return
     */
    @ApiOperation("获取我的客群列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "页码"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数"),
            @ApiImplicitParam(paramType = "query", name = "customersName", value = "客群名称"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态"),
            @ApiImplicitParam(paramType = "query", name = "createTimeStart", value = "创建时间筛选（开始）"),
            @ApiImplicitParam(paramType = "query", name = "createTimeEnd", value = "创建时间筛选（结束）"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeStart", value = "更新时间筛选（开始）"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeEnd", value = "更新时间筛选（结束）")
    })
    @GetMapping("/myList")
    public Result myList(Integer pageNumber, Integer pageSize, String customersName, String status, String createTimeStart, String createTimeEnd, String uptTimeStart, String uptTimeEnd, String dateType) {
        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        return customersService.myList(pageNumber, pageSize, customersName, status, createTimeStart, createTimeEnd, uptTimeStart, uptTimeEnd,dateType);
    }

    @ApiOperation("测试定时更新客群的有效状态")
    @GetMapping("/testUpdateStatus")
    public Result testUpdateStatus() {
        List<String> customersIds = customersMapper.findAllCustomerId();
        List<Filter> filters;
        String newTime;
        if (customersIds != null && !customersIds.isEmpty()) {
            for (String customersId : customersIds) {
                filters = new ArrayList<>();
                customersService.findFilterGroup("-", customersId, filters);
                if (!filters.isEmpty()) {
                    for (Filter filter : filters) {
                        //根据标签id获取其有效状态
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        newTime = sdf.format(new Date());
                        //判断标签是否过期
                        int count = customersMapper.findDimStatus(newTime, filter.getDimId());
                        if (count < 1) {
                            //已过期,设置客群为无效
                            customersMapper.updateCustomersStatus(customersId, "02");
                        }
                    }
                }
            }
        }
        return new Result(CustomersCodes.SUCCESS);
    }

    @ApiOperation(value = "客群保存共享状态", notes = "客群共享")
    @PostMapping("/give")
    public Result give(@RequestBody  @Valid ShareModel shareModel) {
        try{
            customersService.give(shareModel);
        }catch (Exception e){
            log.error("客群共享保存出错", e);
            return new Result(CustomersCodes.FAIL,"客群共享失败！");
        }
        return new Result(CustomersCodes.SUCCESS);
    }
    @ApiOperation(value = "客群共享列表", notes = "客群共享列表")
    @GetMapping("/getShareList")
    public Result getShareList(@ModelAttribute ShareListQueryModel model) {
        try{
            if(model.getPageNumber() == null){
                model.setPageNumber(1);
            }
            if(model.getPageSize() == null){
                model.setPageSize(10);
            }
            return new Result(CustomersCodes.SUCCESS,customersService.getShareList(model));
        }catch (Exception e){
            log.error("客群共享保存出错", e);
            return new Result(CustomersCodes.FAIL,"客群共享失败！");
        }
    }

    @ApiOperation(value = "查看单个客群详情", notes = "查看共享用户列表")
    @GetMapping("/sharedInfo/{customersId}")
    public Result list(@PathVariable @NotBlank String customersId) {
        return new Result(CustomersCodes.SUCCESS,customersService.sharedInfo(customersId));
    }

    @ApiOperation(value = "手动刷新客数定时", notes = "手动刷新客数定时")
    @GetMapping("/refreshCount")
    public Result refreshCount() {
        log.info("更新客群客户数任务 开始");
        HandlePage handlePage;
        int page = 1;
        do{
            CustomersPage<Customers> customersPage = customersService.getDeployAndSeedCustomersByPage(page, 1000);
            List<Customers> content = customersPage.getContent();
            if(!CollectionUtils.isEmpty(content)){
                content.forEach(customers -> {
                    updateAmount(customers);
                });
            }
            handlePage = HandlePage.builder().page(customersPage.getRequestPager()).totalPage(customersPage.getTotalPages()).message("success").finish(customersPage.getTotalPages()<=page).build();
            log.info("更新客群客户数任务：page {}-{}", handlePage.getPage(), handlePage.getMessage());
            page++;
        }while (!handlePage.isFinish());
        log.info("更新客群客户数任务 结束");
        return new Result(CustomersCodes.SUCCESS);
    }

    private void updateAmount(Customers customers) {
        try{
            Customers info = customersService.findOneById(customers.getCustomersId());
            customers.setIndexId(info.getIndexId());
            customers.setDateType(info.getDateType());
            customersService.getCountAmount(customers, info.getQueryModel());
            if(customers.getCustomerAmount()==null){
                return;
            }
            customersService.update(customers);
        }catch (Exception e){
            log.error(customers.getCustomersId()+"更新客群人数出错", e);
        }
    }
}